package com.papa91.banner;

import java.util.Timer;
import java.util.TimerTask;

import com.papa91.activity.EmuBaseActivity;
import com.qq.e.ads.banner.ADSize;
import com.qq.e.ads.banner.AbstractBannerADListener;
import com.qq.e.ads.banner.BannerView;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.TextView;

public class BannerInfo {
	protected String adId;
	protected String appId;
	protected EmuBaseActivity activity;
	protected ViewGroup rootView;
	protected int type;
	protected boolean isCanClose = false;

	public String getAdId() {
		return adId;
	}

	public void setAdId(String adId) {
		this.adId = adId;
	}

	public String getAppId() {
		return appId;
	}

	public void setAppId(String appId) {
		this.appId = appId;
	}

	public Activity getActivity() {
		return activity;
	}

	public void setActivity(EmuBaseActivity activity) {
		this.activity = activity;
	}

	public ViewGroup getRootView() {
		return rootView;
	}

	public void setRootView(ViewGroup rootView) {
		this.rootView = rootView;
	}

	public int getType() {
		return type;
	}

	public void setType(int type) {
		this.type = type;
	}

	public BannerView getBv() {
		return bv;
	}

	public void setBv(BannerView bv) {
		this.bv = bv;
	}

	private BannerView bv;

	public BannerInfo(EmuBaseActivity activity, ViewGroup rootView, String adId, String appId, int type) {
		super();
		this.adId = adId;
		this.appId = appId;
		this.activity = activity;
		this.rootView = rootView;
		this.type = type;
	}

	public void showAd() 
	{

		if (null == bv) 
		{
			isCanClose = type != 8;
			bv = new BannerView(activity, ADSize.BANNER, appId, adId);
			bv.setRefresh(30);

			bv.setADListener(new AbstractBannerADListener() {

				@Override
				public void onNoAD(int arg0) {
					Log.i("AD_DEMO", "BannerNoAD，eCode=" + arg0);
					isCanClose = true;
					closeAd();
				}

				@Override
				public void onADReceiv() {
					Log.i("AD_DEMO", "ONBannerReceive");
					activity.setRootAdViewParentVisible(true);
					if(type == 8)
					{
					Timer timer = new Timer();

					TimerTask time = new TimerTask() {
						@Override
						public void run() {
							// TODO Auto-generated method stub
							handler.sendEmptyMessage(1);
						}
					};
					timer.schedule(time, 3000);
					}
					
				}
			});
		
			rootView.addView(bv);

			this.bv.loadAD();
		}
	}

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == 1) {
				closeAd();
			}
			super.handleMessage(msg);
		};
	};

	public void closeAd() {
	
		if (!isCanClose) {
			isCanClose = true;
			return;
		}
		activity.setRootAdViewParentVisible(false);
		isCanClose = false;
		if (null == bv)
			return;
		rootView.removeView(bv);
		rootView.destroyDrawingCache();
		bv = null;
		
	}

}
